package com.lisp.springframework.tx.service;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.lisp.springframework.tx.dao.InnerInvokeDao;
import com.lisp.springframework.tx.dao.JdbcTemplateDao;
import com.lisp.springframework.tx.model.Foo;

@Service
public class PropagationServiceImpl implements PropagationService {

    @Autowired
    private JdbcTemplateDao fooDao;
    
    @Autowired
    private InnerInvokeDao innerInvokeDao;
    
    /** 最外层的事务和内层的多个事务共用一个数据库连接，即: 多个逻辑事务共用一个物理事务 */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public void testPropagationRequired() {
        Foo foo = new Foo();
        foo.setId(System.currentTimeMillis());
        foo.setUpdateDate(new Date());
        foo.setWorkId(1);
        
        try {
            foo.setId(null);
            fooDao.insert(foo);
        } catch (Exception e) {
            // 欺骗外层事务，以测试内层事务silent fail是否会造成外层事务部分提交
            System.out.println("Error: 内层逻辑事务抛出异常");
        }

        System.out.println("test propagationRequired");
    }
    
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public void testPropagationRequiredNew() {
        Foo foo = new Foo();
        foo.setId(System.currentTimeMillis());
        foo.setUpdateDate(new Date());
        foo.setWorkId(1);
        
        try {
            foo.setId(null);
            innerInvokeDao.singleInsert(foo);
        } catch (Exception e) {
            // 欺骗外层事务，以测试内层事务silent fail是否会造成外层事务部分提交
            System.out.println("Error: 内层逻辑事务抛出异常");
        }
    }
}
